<!-- eslint-disable no-unreachable -->
<template>
  <div
    class="resume-options"
    v-loading="loading"
  >
    <el-form
      :model="formState"
      name="options"
      label-position="right"
      label-width="5em"
    >
      <el-form-item
        name="positionId"
        label="应聘职位"
        has-feedback
      >
        <el-select
          v-model="formState.positionId"
          placeholder="请选择"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="item in posList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        name="depId"
        label="应聘部门"
        has-feedback
      >
        <el-tree-select
          placeholder="请选择"
          v-model="formState.depId"
          style="width: 100%"
          :data="depList"
          :render-after-expand="false"
          :check-strictly="true"
          filterable
        />
      </el-form-item>

      <el-form-item
        name="remark"
        label="备注"
        has-feedback
      >
        <el-input
          v-model="formState.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入"
        />
      </el-form-item>

      <div class="btn-footer">
        <el-dropdown
          split-button
          type="primary"
          @click="() => submitForm(buttonMode)"
        >
          {{ buttonMode === 1 ? "保存到待筛选" : "保存到已筛选" }}
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeButtonMode">{{
                buttonMode === 1 ? "保存到已筛选" : "保存到待筛选"
              }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button
          html-type="submit"
          @click="
            () => {
              this.submitForm(0)
            }
          "
        >保存到简历库</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import equal from "fast-deep-equal"
import { getFromStorage, dataURLtoBlob } from "../../lib"
import html2canvas from 'html2canvas'


export default {
  name: "ResumeOptions",
  props: {
    data: Object,
    externalForm: Object,
    repeatResume: Object || undefined,
    domToBeSaveImg: Object || undefined
  },

  data() {
    return {
      loading: false,
      buttonMode: 1,
      formState: {},
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
      },
      depList: [],
      posList: [],
      labelList: [],
      prevResume: undefined,
    }
  },
  methods: {
    changeButtonMode() {
      this.buttonMode = this.buttonMode === 1 ? 2 : 1
    },

    async submitForm(_status) {
      const values = this.formState
      console.log("onFinish values and status:", values, _status)
      this.loading = true
      let repeatResumeId
      if(this.repeatResume && this.repeatResume.id) repeatResumeId = this.repeatResume.id
      const payload = {
        ...this.data,
        ...values,
        ...this.externalForm,
        type: 0,
        // 0:沉淀 1:待筛选 2:已筛选 3:已安排 4:通过 5:已取消 6:已淘汰 7:拟录用 8:确认录用 9:已发offer 10:放弃录用 11:放弃入职 12:已入职
        status: _status,
        repeatResumeId,
      }

      if (equal(this.prevResume, payload)) {
        this.$message.info("简历已保存，请勿重复保存~")
        this.loading = false
        return
      }

      try {
        const HRMS_LOGIN_HOST = await getFromStorage("HRMS_LOGIN_HOST")
        const [originFileUrlRes, resumeId] = await Promise.all([
          this.convertDomToImg(),
          this.axios.post(
            HRMS_LOGIN_HOST + "/hrms/recruit/assistant/saveResume",
            payload,
          ),
        ])

        const fileUrl = originFileUrlRes ? (originFileUrlRes.message || originFileUrlRes.result) : null

        if(fileUrl && resumeId){
          this.axios.post(
            HRMS_LOGIN_HOST + "/hrms/recruit/resumebase/updateFileUrl",
            {
              baseId: resumeId,
              fileUrl,
            },
          )
        }

        this.$message.success("保存成功")
        this.prevResume = payload
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },

    async convertDomToImg(){
      const originalDom = this.domToBeSaveImg
      if(!originalDom) return

      const oldStyle = {
        width: originalDom.style.width,
        height: originalDom.style.height,
        maxWidth: originalDom.style.maxWidth,
        maxHeight: originalDom.style.maxHeight,
      }
      originalDom.style.width = `${originalDom.scrollWidth}px`
      originalDom.style.height = `${originalDom.scrollHeight}px`
      originalDom.style.maxWidth = 'none'
      originalDom.style.maxHeight = 'none'

      const options = {
        width: originalDom.scrollWidth,
        height: originalDom.scrollHeight,
      }
      const canvas = await html2canvas(originalDom, options)
      originalDom.style.width = oldStyle.width
      originalDom.style.height = oldStyle.height
      originalDom.style.maxWidth = oldStyle.maxWidth
      originalDom.style.maxHeight = oldStyle.maxHeight
      // Convert canvas to a PNG data URL
      const dataURL = canvas.toDataURL("image/png")

      // Convert binary data to a Blob
      const blob = dataURLtoBlob(dataURL)

      // Create a File object from the Blob
      const picFile = new File([blob], `${Date.now()}.png`, { type: "image/png" })

      const forms = new FormData()
      forms.append('file', picFile)
      try {
        const HRMS_LOGIN_HOST = await getFromStorage("HRMS_LOGIN_HOST")
        const fileUrl = await this.axios.post(
          HRMS_LOGIN_HOST + "/hrms/sys/common/uploadPicToPdf",
          forms,
          {
            headers:{
              'Content-Type':'multipart/form-data',
              withFullResponse: true
            }
          }
        )
        return fileUrl
      } catch (error) {
        console.log('保存简历的原始图片失败', error)
      }
    },

    onFinishFailed(errorInfo) {
      console.log("onFinishFailed:", errorInfo)
    },

    async initValues() {
      const HRMS_LOGIN_HOST = await getFromStorage("HRMS_LOGIN_HOST")
      const [
        depList,
        posRes,
        // labelList,
      ] = await Promise.all([
        // 部门列表
        this.axios.get(HRMS_LOGIN_HOST + "/hrms/sys/sysDepart/queryTreeList"),
        // 职位列表
        this.axios.get(
          HRMS_LOGIN_HOST + "/hrms/recruit/position/list?pageSize=99999"
        ),
        // 标签列表
        // this.axios.get('/hrms/recruit/label/list')
      ])

      const posList = posRes.records || []
      // 把depList树形数据中的id字段转为value,departName字段转为label
      const convertDepList = (depList) => {
        return depList.map((item) => {
          const { id, departName, children } = item
          return {
            value: id,
            label: departName,
            children: children?.length ? convertDepList(children) : [],
          }
        })
      }

      this.depList = convertDepList(depList)
      this.posList = posList
      // this.labelList = labelList
    },
  },
  created() {
    this.initValues()
  },
  unmounted() {
    this.prevResume = undefined
  },
}
</script>

<style lang="less" scoped>
@import "./style.less";
</style>
